#!/bin/bash

# This script requires env var $MAXMIND_LICENSE_KEY to be set
if [ -z ${MAXMIND_LICENSE_KEY} ];
then
  echo "Need \$MAXMIND_LICENSE_KEY";
  exit 1
fi

editions=(GeoLite2-ASN GeoLite2-Country GeoLite2-City)

cd redist

did_update_anything=0

for edition in ${editions[*]}
do
  echo -e "\nDownloading checksum for latest version of ${edition}..."
  curl -s "https://download.maxmind.com/app/geoip_download?edition_id=${edition}&license_key=${MAXMIND_LICENSE_KEY}&suffix=tar.gz.md5" -o ${edition}.tar.gz.remote.md5

  if [ -f "$edition.tar.gz.md5" ];
  then
	 echo "Checking against current version..."
	 remote=`cat ${edition}.tar.gz.remote.md5`
	 local=`cat ${edition}.tar.gz.md5`
	 echo "Remote: ${remote}"
	 echo "Local: ${local}"
	 if [ "$remote" == "$local" ];
	 then
		echo -e "\033[32;1m${edition} is already up to date\033[0m"
		rm ${edition}.tar.gz.remote.md5
		continue
	 else
		echo "Update available!"
	 fi
  fi

	echo "Cleaning previous version from git history..."
	cd ..
	./scripts/clean-git-objects ${edition}
	stat=$?
	if [ $stat -ne 0 ]
	then
		echo "Git objects cleaning failed with ${stat} exit code"
		exit 1
	fi
	cd redist

  echo "Downloading ${edition}..."
  curl -s "https://download.maxmind.com/app/geoip_download?edition_id=${edition}&license_key=${MAXMIND_LICENSE_KEY}&suffix=tar.gz" -o ${edition}.tar.gz

  echo "Verifying checksum..."
  remote=`cat ${edition}.tar.gz.remote.md5`
  local=`md5sum ${edition}.tar.gz | awk '{print $1;}'`
	echo "Remote: ${remote}"
	echo "Local: ${local}"
  if [ "$remote" != "$local" ];
  then
	 echo -e "\033[31;1mChecksums didn't match: failed download for ${edition}\033[0m"
	 exit 1
  else
	 rm ${edition}.tar.gz.remote.md5
	 echo ${local} > ${edition}.tar.gz.md5
	 did_update_anything=1
  fi

  echo "Extracting database..."
  tar -zxf ${edition}.tar.gz --wildcards '*.mmdb' --strip-components 1

  echo "Calculating database checksum for redistribution..."
  calculated=`sha384sum ${edition}.mmdb | awk '{print $1;}'`
	echo "New checksum: ${calculated}"
  echo "${calculated}" > ${edition}.mmdb.sha384

	echo "Committing update..."
	cd ..
	./scripts/commit-database ${edition}
	stat=$?
	if [ $stat -ne 0 ]
	then
		echo "Committing failed with ${stat} exit code"
		exit 1
	fi
	cd redist

  echo -e "\033[32;1mDatabase ${edition} successfully updated\033[0m"
done

echo -e "\n\033[1mAll databases processed\033[0m"

if [ $did_update_anything -eq 1 ];
then
	exit 0
else
	exit 65
fi
